package cn.xiyun.xiyuncc.MQ.theTransactionListener;

import cn.xiyun.xiyuncc.domain.PayFlow;
import cn.xiyun.xiyuncc.domain.PayOrder;
import cn.xiyun.xiyuncc.service.IPayFlowService;
import cn.xiyun.xiyuncc.service.IPayOrderService;
import cn.xiyun.xiyuncc.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

@Component
@RocketMQTransactionListener(txProducerGroup = "Transaction-AlipayNotify-group")
public class AlipayNotifyTransactionListener implements RocketMQLocalTransactionListener {
    @Autowired
    private IPayFlowService payFlowService;
    @Autowired
    private IPayOrderService payOrderService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        PayFlow payFlow = JSON.parseObject(o.toString(), PayFlow.class);
        // 添加 payFlow表数据
        boolean insert = payFlowService.insert(payFlow);
        if (!insert) return RocketMQLocalTransactionState.ROLLBACK;

        String outTradeNo = payFlow.getOutTradeNo();
        //  根据订单号查询中支付单
        PayOrder payOrder = payOrderService.selectOrderNo(outTradeNo);
        if (payOrder == null) return RocketMQLocalTransactionState.ROLLBACK;

        // 更改支付单状态
        payOrder.setPayStatus(PayOrder.PAY_SUCCEED);
        boolean b = payOrderService.updateById(payOrder);
        if (!b) return RocketMQLocalTransactionState.ROLLBACK;

        return RocketMQLocalTransactionState.COMMIT;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        // 根据订单号查询支付单
        String string = message.toString();
        PayOrder payOrder = payOrderService.selectOrderNo(string);
        // 非空判断
        if (payOrder == null) return RocketMQLocalTransactionState.ROLLBACK;
        // 判断支付单状态
        if (payOrder.getPayStatus() == PayOrder.PAY_SUCCEED) return RocketMQLocalTransactionState.COMMIT;

        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
